package com.ky.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ky.tms.entity.TmsCarOil;
import com.ky.tms.entity.TmsOilRechange;
import com.ky.tms.mapper.TmsCarOilMapper;
import com.ky.tms.mapper.TmsOilRechangeMapper;
import com.ky.tms.service.ITmsOilRechangeService;
import com.ky.tms.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 2020-06-04
 */
@Service
public class TmsOilRechangeServiceImpl extends ServiceImpl<TmsOilRechangeMapper, TmsOilRechange> implements ITmsOilRechangeService {

    @Autowired
    private TmsOilRechangeMapper tmsOilRechangeMapper;

    @Autowired
    private TmsCarOilMapper tmsCarOilMapper;

    @Override
    public IPage<TmsOilRechange> oilPage(TmsOilRechange tmsOilRechange, Long limit, Long pages) {
        IPage<TmsOilRechange> page = new Page(pages, limit);
        QueryWrapper<TmsOilRechange> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(tmsOilRechange.getOilNo())){
            wrapper.like("oil_no", tmsOilRechange.getOilNo());
        }

        if(tmsOilRechange.getCreateTimeArray() != null && tmsOilRechange.getCreateTimeArray().size()>0){
            wrapper.ge("rechange_date", DateUtil.strToLocalDate(tmsOilRechange.getCreateTimeArray().get(0),"yyyy-MM-dd"));
            wrapper.le("rechange_date", DateUtil.strToLocalDate(tmsOilRechange.getCreateTimeArray().get(1),"yyyy-MM-dd"));
        }
        wrapper.eq("is_valid", 1);
        wrapper.orderByDesc("create_time");
        page = this.page(page, wrapper);
        List<TmsOilRechange> records = page.getRecords();
        for(TmsOilRechange record : records){
            QueryWrapper<TmsOilRechange> w1 = new QueryWrapper<>();
            w1.eq("oil_no", record.getOilNo());
            w1.lt("id", record.getId());
            w1.eq("is_valid", 1);
            w1.orderByDesc("id");
            List<TmsOilRechange> tmsOilRechanges = tmsOilRechangeMapper.selectList(w1);

            QueryWrapper<TmsCarOil> w2 = new QueryWrapper<>();
            w2.eq("oil_no", record.getOilNo());
            if(tmsOilRechanges.size()>1) {
                w2.ge("oil_time", tmsOilRechanges.get(0).getRechangeDate());
            }
            w2.le("oil_time", record.getRechangeDate());
            w2.eq("is_valid", 1);
            List<TmsCarOil> tmsCarOils = tmsCarOilMapper.selectList(w2);
            record.setTmsCarOils(tmsCarOils);
        }

        return page;
    }
}
